<?php

class ControllerStockStockSearch extends Controller {
	
	//初始化
	public function index() {

		$this->load->language('stock/stocksearch');

		$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('stock/stocksearch');

		$this->getList();

    }

	//获取商品库存列表
	private function getList(){

		$url = '';
		
		/*筛选条件*/
		if (isset($this->request->get['filter_warehouse'])) {
			$filter_warehouse = $this->request->get['filter_warehouse'];
			$url .= '&filter_warehouse=' . $this->request->get['filter_warehouse'];
		} else {
			$filter_warehouse = null;
		}

		if (isset($this->request->get['filter_product_code'])) {
			$filter_product_code = $this->request->get['filter_product_code'];
			$url .= '&filter_product_code=' . $this->request->get['filter_product_code'];
		} else {
			$filter_product_code = null;
		}

		if (isset($this->request->get['filter_warehouse_position'])) {
			$filter_warehouse_position = trim($this->request->get['filter_warehouse_position']);
			$url .= '&filter_warehouse_position=' . $filter_warehouse_position;
		} else {
			$filter_warehouse_position = null;
		}

		if (isset($this->request->get['filter_sku'])) {
			$filter_sku = trim($this->request->get['filter_sku']);
			$url .= '&filter_sku=' . $filter_sku;
		} else {
			$filter_sku = null;
		}

        if (isset($this->request->get['filter_vendor'])) {
            $filter_vendor = intval($this->request->get['filter_vendor']);
            $url .= '&filter_vendor=' . $filter_vendor;
        } else {
            $filter_vendor = null;
        }

		if(isset($this->request->get['page'])){
			$page = $this->request->get['page'];
			$url .= '&page=' . $page;
		}
		else{
			$page = 1;
		}

		if(isset($this->request->get['sort'])){
			$sort = $this->request->get['sort'];
			$url .= '&sort=' . $sort;
		}
		else{
			$sort = 'i.id';
		}
    
		if(isset($this->request->get['order'])){
			$order = $this->request->get['order'];
			$url .= '&order=' . $order;
		}
		else{
			$order = 'ASC';
		}

		$filter_data = array(
			'filter_warehouse' =>$filter_warehouse,
			'filter_product_code' =>$filter_product_code,
			'filter_warehouse_position' =>$filter_warehouse_position,
			'filter_sku' =>$filter_sku,
            'filter_vendor' => $filter_vendor,
			'sort'   => $sort,
			'order' => $order,
			'start'  => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'   => $this->config->get('config_limit_admin')
		);
		
		$data['filter_warehouse'] = $filter_warehouse;
		$data['filter_product_code'] = $filter_product_code;
		$data['filter_warehouse_position'] = $filter_warehouse_position;
		$data['filter_sku'] = $filter_sku;
		/*筛选条件*/
		
		/*面包屑导航栏*/
		$data['heading_title'] = $this->language->get('heading_title');
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('stock/stocksearch', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);
		/*面包屑导航栏*/
		
		/*标题*/
		$data['text_list'] = $this->language->get('text_list');
		/*标题*/
		
		/*筛选条件*/
		$data['entry_product_name'] = $this->language->get('entry_product_name');
		$data['entry_warehouse'] = $this->language->get('entry_warehouse');
		$data['entry_warehouse_position'] = $this->language->get('entry_warehouse_position');
		$data['entry_sku'] = $this->language->get('entry_sku');
        $data['entry_vendor_name'] = $this->language->get('entry_vendor_name');

		/*筛选条件*/
		
		/*表格列*/
		$data['text_no_results'] = $this->language->get('text_no_results');
		
		$data['column_warehouse_name'] = $this->language->get('column_warehouse_name');
		$data['column_position1'] = $this->language->get('column_position1');
		$data['column_position2'] = $this->language->get('column_position2');
		$data['column_product_code'] = $this->language->get('column_product_code');
		$data['column_product_sku'] = $this->language->get('column_product_sku');
		$data['column_product_name'] = $this->language->get('column_product_name');
		$data['column_product_option'] = $this->language->get('column_product_option');
        $data['column_vendor_name'] = $this->language->get('column_vendor_name');
		$data['column_account_quantity'] = $this->language->get('column_account_quantity');
		$data['column_available_quantity'] = $this->language->get('column_available_quantity');
		$data['column_safe_quantity'] = $this->language->get('column_safe_quantity');
		$data['column_action'] = $this->language->get('column_action');
		/*表格列*/

		$data['token'] = $this->session->data['token'];
		$data['can_edit'] = $this->user->hasPermission('modify', 'stock/stocksearch');
		
		/*筛选相关*/
		$data['button_filter'] = $this->language->get('button_filter');
		$warehouses = $this->model_stock_stocksearch->getWarehouses(); //获取全部仓库
		
		foreach ($warehouses as $value){

			$data["warehouses"][] = array(
				'warehouse_id' => $value['warehouse_id'],
				'name' => $value['name']
			);
		}
        /*筛选相关*/
        /*
         * 新增供应商筛选
         * @author sonicsjh
         */
        $this->load->model('catalog/vendor');
        $vendorList = $this->model_catalog_vendor->getVendorsList();
        foreach ($vendorList as $vendor) {
            $data['vendors'][$vendor['vendor_id']] = $vendor['name'];
        }
        /*
         * @author sonicsjh
         */
        
		$inventories_total = $this->model_stock_stocksearch->getTotalInventories($filter_data); //库存总计数量
		$results = $this->model_stock_stocksearch->getInventories($filter_data); //库存数据

		foreach ($results as $result){

			$data['inventories'][] = array(
				'warehouse_name' => $result['warehouse_name'],
				'position1' => $result['position1'],
				'position2' => $result['position2'],
				'product_name' => $result['product_name'],
				'product_code' => $result['product_code'],
				'sku' => $result['sku'],
				'product_option' => $result['product_option'],
                'vendor_name' => $data['vendors'][$result['vendor']],//@author sonicsjh
				'account_quantity' => $result['account_quantity'],
				'available_quantity' => $result['available_quantity'],
				'safe_quantity' => $result['safe_quantity'],
				'view' => $this->url->link('stock/stocksearch/view', 'token=' . $this->session->data['token'] . '&id=' . $result['id'] . $url, 'SSL'),
				'edit' => $this->url->link('stock/stocksearch/edit', 'token=' . $this->session->data['token'] . '&id=' . $result['id'] . $url, 'SSL')
			);

		}

		/*分页*/
		$pagination = new Pagination();
		$pagination->total = $inventories_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('stock/stocksearch', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();
		$data['results'] = sprintf($this->language->get('text_pagination'), ($inventories_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($inventories_total - $this->config->get('config_limit_admin'))) ? $inventories_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $inventories_total, ceil($inventories_total / $this->config->get('config_limit_admin')));
		/*分页*/
		
		//加载头部侧边栏底部
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');
		
		//返回模板页
		$this->response->setOutput($this->load->view('stock/stocksearch.tpl', $data));

	}
	
	//编辑商品库存
	public function edit(){

		$this->load->language('stock/stocksearch');
		$this->document->setTitle($this->language->get('heading_title'));
		$this->load->model('stock/stocksearch');

		$url = '';
			
		/*返回筛选条件*/
		if (isset($this->request->get['filter_warehouse'])) {
			$url .= '&filter_warehouse=' . $this->request->get['filter_warehouse'];
		}

		if (isset($this->request->get['filter_product_code'])) {
			$url .= '&filter_product_code=' . $this->request->get['filter_product_code'];
		}

		if (isset($this->request->get['filter_warehouse_position'])) {
			$url .= '&filter_warehouse_position=' . $this->request->get['filter_warehouse_position'];
		}

		if (isset($this->request->get['filter_sku'])) {
			$url .= '&filter_sku=' . $this->request->get['filter_sku'];
		}

		if (isset($this->request->get['filter_vendor'])) {
			$url .= '&filter_vendor=' . $this->request->get['filter_vendor'];
		}

		if(isset($this->request->get['page'])){
			$url .= '&page=' . $this->request->get['page'];
		}

		if(isset($this->request->get['sort'])){
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if(isset($this->request->get['order'])){
			$url .= '&order=' . $this->request->get['order'];
		}
		/*返回筛选条件*/

		if(($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()){

			 $this->model_stock_stocksearch->editInventory($this->request->get['id'], $this->request->post);

			 $this->session->data['success'] = $this->language->get('text_success');

			$this->response->redirect($this->url->link('stock/stocksearch', 'token=' . $this->session->data['token'] . $url, 'SSL'));

		}

		/*面包屑导航栏*/
		$data['heading_title'] = $this->language->get('heading_title');
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('stock/stocksearch', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);
		/*面包屑导航栏*/

		/*右上操作按钮*/
		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');
		$data['cancel'] = $this->url->link('stock/stocksearch', 'token=' . $this->session->data['token'] . $url, 'SSL');
		/*右上操作按钮*/

		$data['action'] = $this->url->link('stock/stocksearch/edit', 'token=' . $this->session->data['token'] . '&id=' . $this->request->get['id'] . $url, 'SSL');

		/*标题*/
		$data['text_edit'] = $this->language->get('text_edit');
		/*标题*/
		
		$data['entry_warehouse'] = $this->language->get('entry_warehouse');
		$data['entry_product_name'] = $this->language->get('entry_product_name');
		$data['entry_product_code'] = $this->language->get('entry_product_code');
		$data['entry_option_name'] = $this->language->get('entry_option_name');
		$data['entry_sku'] = $this->language->get('entry_sku');
		$data['entry_position1'] = $this->language->get('entry_position1');
		$data['entry_position2'] = $this->language->get('entry_position2');
		$data['entry_safe_quantity'] = $this->language->get('entry_safe_quantity');
		
		//获取此id库存基本信息
		$inventory_info = $this->model_stock_stocksearch->getInventory($this->request->get['id']); 
		$data['warehouse_name'] = $inventory_info['warehouse_name'];
		$data['product_name'] = $inventory_info['product_name'];
		$data['product_code'] = $inventory_info['product_code'];
		$data['option_name'] = $inventory_info['option_name'];
		$data['product_sku'] = $inventory_info['product_sku'];

		if(isset($this->request->post['position1'])){
			$data['position1'] = $this->request->post['position1'];
		}
		elseif(!empty($inventory_info)){
			$data['position1'] = $inventory_info['position1'];
		}
		else{  
			$data['position1'] = '';
		}

		if(isset($this->request->post['position2'])){
			$data['position2'] = $this->request->post['position2'];
		}
		elseif(!empty($inventory_info)){
			$data['position2'] = $inventory_info['position2'];
		}
		else{  
			$data['position2'] = '';
		}

		if(isset($this->request->post['safe_quantity'])){
			$data['safe_quantity'] = $this->request->post['safe_quantity'];
		}
		elseif(!empty($inventory_info)){
			$data['safe_quantity'] = $inventory_info['safe_quantity'];
		}
		else{  
			$data['safe_quantity'] = '';
		}

		//加载头部侧边栏底部
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		//返回模板页
		$this->response->setOutput($this->load->view('stock/stocksearch_edit.tpl', $data));

	}
	
	//查看商品库存
	public function view(){
		
		$this->load->language('stock/stocksearch');
		$this->document->setTitle($this->language->get('heading_title'));
		$this->load->model('stock/stocksearch');
		
		$id = $this->request->get['id'];

		if(isset($this->request->get['page'])){
			$page = $this->request->get['page'];
			$url .= '&page=' . $page;
		}
		else{
			$page = 1;
		}

		$start = ($page - 1) * $this->config->get('config_limit_admin');
		$limit = $this->config->get('config_limit_admin');

		//获取此id库存基本信息
		$inventory_info = $this->model_stock_stocksearch->getInventory($id); 
		$data['inventory'] = $inventory_info;	

		/*右上操作按钮*/
		$data['export_url'] = URL('stock/stocksearch/exportHistory', 'token=' . $this->session->data['token'] . '&id='.$id.'&warehouse='.$inventory_info['warehouse_name']);
		$data['button_cancel'] = $this->language->get('button_cancel');
		$data['cancel'] = $this->url->link('stock/stocksearch', 'token=' . $this->session->data['token'] . $url, 'SSL');
		/*右上操作按钮*/

		/*面包屑导航栏*/
		$data['heading_title'] = $this->language->get('heading_title');
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('stock/stocksearch', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);
		/*面包屑导航栏*/
		
		//获取此id库存相关单据
		$in_history = $this->model_stock_stocksearch->getInHistory($id); //入库
		$out_history = $this->model_stock_stocksearch->getOutHistory($id); //出库
		$trim_history = $this->model_stock_stocksearch->getTrimHistory($id); //损益

		$group_history = array_merge($in_history, $out_history,$trim_history);
		$inventory_histories = $this->model_stock_stocksearch->getInventoryHistory($group_history);
		
		$total = count($inventory_histories);
		$data['inventory_histories'] = array_slice($inventory_histories,$start,$limit); //分页取数据

		foreach($data['inventory_histories'] as &$value){

			if($value['type'] =='in'){
				$value['type'] = '入库单';
			}
			else if($value['type'] =='out'){
				$value['type'] = '出库单';
			}
			else if($value['type'] =='trim'){
				$value['type'] = '损益单';
				$value['status'] = getTrimOrderStatus()[$value['status']];
			}

		}

		/*分页*/
		$pagination = new Pagination();
		$pagination->total = $total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('stock/stocksearch/view', 'id='.$id.'&token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();
		$data['results'] = sprintf($this->language->get('text_pagination'), ($total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($total - $this->config->get('config_limit_admin'))) ? $total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $total, ceil($total / $this->config->get('config_limit_admin')));
		/*分页*/

		//加载头部侧边栏底部
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		//返回模板页
		$this->response->setOutput($this->load->view('stock/stocksearch_view.tpl', $data));

	}
	
	//导出库存
	public function exportInventory(){
		
		$this->load->language('stock/stocksearch');
		$this->document->setTitle($this->language->get('heading_title'));
		$this->load->model('stock/stocksearch');

		/*筛选条件*/
		if (isset($this->request->get['filter_warehouse'])) {
			$filter_warehouse = $this->request->get['filter_warehouse'];
			$url .= '&filter_warehouse=' . $this->request->get['filter_warehouse'];
		} else {
			$filter_warehouse = null;
		}

		if (isset($this->request->get['filter_product_code'])) {
			$filter_product_code = $this->request->get['filter_product_code'];
			$url .= '&filter_product_code=' . $this->request->get['filter_product_code'];
		} else {
			$filter_product_code = null;
		}

		if (isset($this->request->get['filter_warehouse_position'])) {
			$filter_warehouse_position = trim($this->request->get['filter_warehouse_position']);
			$url .= '&filter_warehouse_position=' . $filter_warehouse_position;
		} else {
			$filter_warehouse_position = null;
		}

		if (isset($this->request->get['filter_sku'])) {
			$filter_sku = trim($this->request->get['filter_sku']);
			$url .= '&filter_sku=' . $filter_sku;
		} else {
			$filter_sku = null;
		}

		if(isset($this->request->get['sort'])){
			$sort = $this->request->get['sort'];
			$url .= '&sort=' . $sort;
		}
		else{
			$sort = 'i.id';
		}
    
		if(isset($this->request->get['order'])){
			$order = $this->request->get['order'];
			$url .= '&order=' . $order;
		}
		else{
			$order = 'ASC';
		}

		$filter_data = array(
			'filter_warehouse' =>$filter_warehouse,
			'filter_product_code' =>$filter_product_code,
			'filter_warehouse_position' =>$filter_warehouse_position,
			'filter_sku' =>$filter_sku,
			'sort'   => $sort,
			'order' => $order
		);
		/*筛选条件*/

		$results = $this->model_stock_stocksearch->getInventories($filter_data);

		foreach ($results as $result){
            if ('' == $result['product_name']){
                continue;
			}
			$pcode = substr($result['product_code'], 0,10);
			$sql = "SELECT product.product_class1, (SELECT category_description.`name` FROM `category_description` WHERE category_description.category_id = product.product_class1 ) AS 'name1', product.product_class2, (SELECT category_description.`name` FROM `category_description` WHERE category_description.category_id = product.product_class2 ) AS 'name2', product.product_class3, (SELECT category_description.`name` FROM `category_description` WHERE category_description.category_id = product.product_class3 ) AS 'name3', product.product_code FROM `product` WHERE  product_code = ".$pcode;
			$query = $this->db->query($sql);
			$data['inventories'][] = array(
				'warehouse_name' => $result['warehouse_name'],
				'product_class1' => $query->row['product_class1'],
				'name1' => $query->row['name1'],
				'product_class2' => $query->row['product_class2'],
				'name2' => $query->row['name2'],
				'product_class3' => $query->row['product_class3'],
				'name3' => $query->row['name3'],
				'position1' => $result['position1'],
				'position2' => $result['position2'],
				'product_name' => $result['product_name'],
				'product_code' => $result['product_code'],
				'sku' => $result['sku'],
				'product_option' => $result['product_option'],
				'account_quantity' => $result['account_quantity'],
				'available_quantity' => $result['available_quantity'],
				'safe_quantity' => $result['safe_quantity'],
                'product_cost' => $result['product_cost'],
                'cost_total' => $result['product_cost']*$result['available_quantity'],
			);

		}
		
		/*excel相关*/
		$this->load->library('PHPExcel/PHPExcel');
	    $objPHPExcel = new PHPExcel();    
	    $objProps = $objPHPExcel->getProperties();    
	    $objProps->setCreator("Think-tec");
	    $objProps->setLastModifiedBy("Think-tec");    
	    $objProps->setTitle("Think-tec Contact");    
	    $objProps->setSubject("Think-tec Contact Data");    
	    $objProps->setDescription("Think-tec Contact Data");    
	    $objProps->setKeywords("Think-tec Contact");    
	    $objProps->setCategory("Think-tec");
	    $objPHPExcel->setActiveSheetIndex(0);     
	    $objActSheet = $objPHPExcel->getActiveSheet(); 
		/*excel相关*/
		
		/*添加库存信息*/
		$objActSheet->setTitle('库存信息');
		$col1 = 'A';
		$headers = array("仓库","库位1","库位2","商品名称","大分类","大分类编号","中分类","中分类编号","小分类","小分类编号","商品编码","条形码","选项","财务数量","可用数量","安全库存","成本单价","成本小计");
		$keys = array("warehouse_name","position1","position2","product_name","name1","product_class1","name2","product_class2","name3","product_class3","product_code","sku","product_option","account_quantity","available_quantity","safe_quantity","product_cost","cost_total");

		//头部
		foreach($headers as $header){
			$objActSheet->setCellValue($col1++.'1', $header);  
		}

		//内容
		$i = 2;
		foreach ($data['inventories'] as $value) {
			$col2 = 'A';
			foreach($keys as $key){
				$objActSheet->setCellValueExplicit($col2++.$i, $value[$key], PHPExcel_Cell_DataType::TYPE_STRING);
			}
			$i++;
		}
		/*添加库存信息*/

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		
		/*excel相关*/
		ob_end_clean();
	    // Redirect output to a client’s web browser (Excel2007)
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	    header('Content-Disposition: attachment;filename="order_'.date('Y-m-d',time()).'.xlsx"');
	    header('Cache-Control: max-age=0');
	    // If you're serving to IE 9, then the following may be needed
	    header('Cache-Control: max-age=1');

	    // If you're serving to IE over SSL, then the following may be needed
	    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	    header ('Pragma: public'); // HTTP/1.0
	    $objWriter->save('php://output'); 
		/*excel相关*/

	    exit;

	}

	//导出相关单据
	public function exportHistory(){
		
		$this->load->language('stock/stocksearch');
		$this->document->setTitle($this->language->get('heading_title'));
		$this->load->model('stock/stocksearch');
		
		/*excel相关*/
		$this->load->library('PHPExcel/PHPExcel');
	    $objPHPExcel = new PHPExcel();    
	    $objProps = $objPHPExcel->getProperties();    
	    $objProps->setCreator("Think-tec");
	    $objProps->setLastModifiedBy("Think-tec");    
	    $objProps->setTitle("Think-tec Contact");    
	    $objProps->setSubject("Think-tec Contact Data");    
	    $objProps->setDescription("Think-tec Contact Data");    
	    $objProps->setKeywords("Think-tec Contact");    
	    $objProps->setCategory("Think-tec");
	    $objPHPExcel->setActiveSheetIndex(0);     
	    $objActSheet = $objPHPExcel->getActiveSheet(); 
		/*excel相关*/

		//获取此id库存相关单据
		$id = $this->request->get['id'];
		$in_history = $this->model_stock_stocksearch->getInHistory($id); //入库
		$out_history = $this->model_stock_stocksearch->getOutHistory($id); //出库
		$trim_history = $this->model_stock_stocksearch->getTrimHistory($id); //损益

		foreach ($in_history as $result){

			if($result['stock_status'] == 2){
				$acq = $result['qty'];
			}
			else{
				$acq = 0;
			}

			$data['in_history'][] = array(
				'warehouse_name' => $this->request->get['warehouse'],
				'id' => $result['id'],
				'refer_name' => $result['refer_name']."(".$result['refer_id'].")",
				'account_quantity' => $acq,
				'available_quantity' => $result['qty'],
				'user_name' => $result['user_name'],
				'date_added' => $result['date_added'],
				'status' => $result['status']
			);

		}

		foreach ($out_history as $result){

			if($result['stock_status'] == 2){
				$acq = $result['calculate'].$result['qty'];
			}
			else{
				$acq = 0;
			}

			$data['out_history'][] = array(
				'warehouse_name' => $this->request->get['warehouse'],
				'id' => $result['id'],
				'refer_name' => $result['refer_name']."(".$result['refer_id'].")",
				'account_quantity' => $acq,
				'available_quantity' => $result['calculate'].$result['qty'],
				'user_name' => $result['user_name'],
				'date_added' => $result['date_added'],
				'status' => $result['status']
			);

		}

		foreach ($trim_history as $result){

			$data['trim_history'][] = array(
				'warehouse_name' => $this->request->get['warehouse'],
				'id' => $result['id'],
				'account_quantity' => $result['qty'],
				'available_quantity' => $result['qty'],
				'user_name' => $result['user_name'],
				'date_added' => $result['date_added'],
				'status' => getTrimOrderStatus()[$result['status']]
			);

		}
		
		/*添加入库单*/
		$objActSheet->setTitle('入库单');
		$col1 = 'A';
		$headers = array("入库仓库","单号","相关单据","对财务数量影响","对可用数量影响","操作员","创建时间","状态");
		$keys = array("warehouse_name","id","refer_name","account_quantity","available_quantity","user_name","date_added","status");

		//头部
		foreach($headers as $header){
			$objActSheet->setCellValue($col1++.'1', $header);  
		}

		//内容
		$i = 2;
		foreach ($data['in_history'] as $value) {
			$col2 = 'A';
			foreach($keys as $key){
				$objActSheet->setCellValueExplicit($col2++.$i, $value[$key], PHPExcel_Cell_DataType::TYPE_STRING);
			}
			$i++;
		}
		/*添加入库单*/

		/*添加出库单*/
		$requisition_sheet = new PHPExcel_Worksheet($objPHPExcel, '出库单');
		$objPHPExcel->addSheet($requisition_sheet);
		$objPHPExcel->setActiveSheetIndex(1);
		$objActSheet = $objPHPExcel->getActiveSheet(); 
		$col1 = 'A';
		$headers = array("出库仓库","单号","相关单据","对财务数量影响","对可用数量影响","操作员","创建时间","状态");
		$keys = array("warehouse_name","id","refer_name","account_quantity","available_quantity","user_name","date_added","status");

		//头部
		foreach($headers as $header){
			$objActSheet->setCellValue($col1++.'1', $header);  
		}

		//内容
		$i = 2;
		foreach ($data['out_history'] as $value) {
			$col2 = 'A';
			foreach($keys as $key){
				$objActSheet->setCellValueExplicit($col2++.$i, $value[$key], PHPExcel_Cell_DataType::TYPE_STRING);
			}
			$i++;
		}
		/*添加出库单*/

		/*添加损益单*/
		$requisition_sheet = new PHPExcel_Worksheet($objPHPExcel, '损益单');
		$objPHPExcel->addSheet($requisition_sheet);
		$objPHPExcel->setActiveSheetIndex(2);
		$objActSheet = $objPHPExcel->getActiveSheet(); 
		$col1 = 'A';
		$headers = array("仓库","单号","对财务数量影响","对可用数量影响","操作员","创建时间","状态");
		$keys = array("warehouse_name","id","account_quantity","available_quantity","user_name","date_added","status");

		//头部
		foreach($headers as $header){
			$objActSheet->setCellValue($col1++.'1', $header);  
		}

		//内容
		$i = 2;
		foreach ($data['trim_history'] as $value) {
			$col2 = 'A';
			foreach($keys as $key){
				$objActSheet->setCellValueExplicit($col2++.$i, $value[$key], PHPExcel_Cell_DataType::TYPE_STRING);
			}
			$i++;
		}
		/*添加损益单*/

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		
		/*excel相关*/
		ob_end_clean();
	    // Redirect output to a client’s web browser (Excel2007)
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	    header('Content-Disposition: attachment;filename="order_'.date('Y-m-d',time()).'.xlsx"');
	    header('Cache-Control: max-age=0');
	    // If you're serving to IE 9, then the following may be needed
	    header('Cache-Control: max-age=1');

	    // If you're serving to IE over SSL, then the following may be needed
	    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	    header ('Pragma: public'); // HTTP/1.0
	    $objWriter->save('php://output'); 
		/*excel相关*/

	    exit;

	}

	//验证表单
	private function validateForm(){

		if(!$this->user->hasPermission('modify', 'stock/stocksearch')){
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if(!$this->error){
			return TRUE;
		}
		else{
			if(!isset($this->error['warning'])){
				$this->error['warning'] = $this->language->get('error_required_data');
			}
			return FALSE;
		}

	}
	
	//autocomplete
	public function autocomplete() {
		
		$json = array();

		if (isset($this->request->get['filter_product'])) {
			$filter_product = trim($this->request->get['filter_product']);
		}
		else{
			$filter_product = '';
		}

		$filter_data = array(
			'filter_product' => $filter_product,
			'start' => 0,
			'limit' => 5
		);

		$this->load->model('stock/stocksearch');

		$results = $this->model_stock_stocksearch->getProducts($filter_data);

		foreach ($results as $result){
			$json[] = array(
				'product_name' => $result['name'],
				'product_code' => $result['product_code']
			);
		}

		$sort_order = array();

		foreach ($json as $key => $value) {
			$sort_order[$key] = $value['name'];
		}

		array_multisort($sort_order, SORT_ASC, $json);

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
	

    public function autocompleteVendor() {
        $json = array();
        $filterVendor = $this->request->get['filter_vendor'];
        $this->load->model('catalog/vendor');
        $vendorList = $this->model_catalog_vendor->getVendorsList();
        foreach ($vendorList as $vendor) {
            if ('' != $filterVendor && false === strpos($vendor['name'], $filterVendor)){
                continue;
            }
            $json[] = array(
                'vendor_id' => $vendor['vendor_id'],
                'vendor_name' => $vendor['name'],
            );
        }
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    
    }
}
?>